package com.example.demo1115.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import jdk.nashorn.internal.parser.Token;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwUtil {
private static final String key="fbs";
    public static String createToken(Map<String,Object> params){
        Map<String,Object> head=new HashMap<>();
        head.put("alg","HS256");
        head.put("typ","JWT");

        Date iss=new Date();

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,30);
        Date expire = nowTime.getTime();
        String token = JWT.create()
                .withHeader(head)
                .withExpiresAt(expire)
                .withIssuedAt(iss)
                .withIssuer("樊博士")
                .withClaim("name", "fbs")
                .withClaim("userInfo", params)
                .sign(Algorithm.HMAC256(key));
        return token;

    }
    public static boolean verifyToken(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(key)).build();
        try {
            DecodedJWT verify = build.verify(token);
            return true;

        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    public static Map<String,Object> parseToken(String token){
        Map<String, Object> userInfo = JWT.decode(token).getClaim("userInfo").asMap();
        return userInfo;
    }

    public static void main(String[] args) {
//        Map<String,Object> map=new HashMap<>();
//        map.put("name","樊博士");
//        map.put("age",18);
//        String token = createToken(map);
//        System.out.println("token = " + token);
//        boolean b = verifyToken("eyJ0eXAiOiKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6eyJuYW1lIjoi5qiK5Y2a5aOrIiwiYWdlIjoxOH0sImlzcyI6IuaoiuWNmuWjqyIsIm5hbWUiOiJmYnMiLCJleHAiOjE2NjkyMDEwODYsImlhdCI6MTY2OTE5OTI4Nn0.NNQTCtYFA2MLg99Nlgs-lCYUY74csQVnoUqQsI3Zb7E");
//        System.out.println("b = " + b);
        Map<String, Object> map = parseToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6eyJuYW1lIjoi5qiK5Y2a5aOrIiwiYWdlIjoxOH0sImlzcyI6IuaoiuWNmuWjqyIsIm5hbWUiOiJmYnMiLCJleHAiOjE2NjkyMDEwODYsImlhdCI6MTY2OTE5OTI4Nn0.NNQTCtYFA2MLg99Nlgs-lCYUY74csQVnoUqQsI3Zb7E");
        System.out.println("map = " + map);

    }
}
